<script setup lang="ts">
import  { ref, computed } from 'vue' 
import { useRouter } from 'vue-router';
import {register} from '@/api/user';
import {closeToast,showLoadingToast }from 'vant';
import {showFailToast } from 'vant';

// const pattern=/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/
const password=ref('')
const psw=ref('')
const router=useRouter()
const tel=JSON.parse(localStorage.getItem('Tel'))

//验证两次密码是否相同来决定注册按钮能否使用
const flag =computed(()=>{
    return password.value!=psw.value|| password.value.length==0
})

//验证两次密码是否相同
const asyncValidator:any = (val:string) =>
      new Promise((resolve) => {
        showLoadingToast('验证中...');

        setTimeout(() => {
          closeToast();
          resolve(val === password.value);
        }, 1000);
      });

//提交表单
function onSubmit(){
    //表单验证，加密
    if(password.value===psw.value){
        register({tel: tel,password:password.value}).then(res=>{
            if(res.data.code==200){
                localStorage.setItem('password',password.value)
                showFailToast(res.data.message)

                //需要传递参数，标记为是从注册页面跳转到登录页面的
                router.push({
                    path:'/login',
                    query:{
                        type:'10086'
                    }
                })
            }else{
                showFailToast('注册失败，请重试')
                router.push('/register/step1')
            }
        })
       
    }
}
</script>

<template>
 <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field
                v-model="password"
                name="密码"
                label="密码"
                placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]"
                />
                <van-field
                v-model="psw"
                type="password"
                name="再次填写密码"
                label="再次填写"
                placeholder="再次填写密码"
                :rules="[{ required: true,message: '两次密码不相同',validator: asyncValidator, }]"
                />
            </van-cell-group>
            <div style="margin: 30px 16px 16px 16px;">
                <van-button :disabled="flag" round block color="#f66" native-type="submit">
                注册
                </van-button>
            </div>
        </van-form>
</template>